﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using System.IO;
using org.in2bits.MyXls;

public partial class shop_FoodList : System.Web.UI.Page
{
    protected string otime
    {
        get
        {
            object o = ViewState["otime"];
            return (o == null) ? "" : o.ToString();
        }
        set
        {
            ViewState["otime"] = value;
        }
    }
    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        UserHelp.IsLogin_Togo(Request.Url.PathAndQuery);
        if (!this.Page.IsPostBack)
        {
            int tid = UserHelp.GetUser_Togo().Unid;
            SqlWhere = "FPMaster= '" + tid + "' and InUse != 'd'";
            BindData();
            PointsInfo model = new Points().GetModel(UserHelp.GetUser_Togo().Unid);
            otime = model.OpenTime;
            Hangjing.Cache.EasyEatCache.GetCacheService().RemoveObject("/shop/shop" + tid + "/food");

            IList<EFoodSortInfo> list = new EFoodSort().GetListByTogoNum(tid);
            if (list.Count == 0)
            {
                string js = "alert('您还没有为此商家添加一个分类,点击确定添加分类');gourl('FoodSortDetail.aspx?tid=" + tid + "');";
                AlertScript.RegScript(Page, js);
                return;
            }
            WebUtility.BindList<EFoodSortInfo>("SortID", "SortName", list, ddlFoodType);


        }
    }

    Foodinfo dal = new Foodinfo();
    protected void BindData()
    {
        this.AspNetPager1.RecordCount = dal.GetCount(SqlWhere);
        this.rptFoodList.DataSource = dal.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, "FoodNo", 1);
        this.rptFoodList.DataBind();
        NoRecord();
    }

    private void NoRecord()
    {
        if (rptFoodList.Items.Count == 0)
        {
            noRecord.Style.Add(HtmlTextWriterStyle.Display, "block");
        }
        else
        {
            noRecord.Style.Add(HtmlTextWriterStyle.Display, "none");
        }
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindData();
    }

    protected void rptFoodList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string type = e.CommandName;
        if (type == "del")
        {
            if (dal.UpdateValue("InUse", "d", "where Unid = (" + e.CommandArgument + ")") > 0)
            {
                AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作成功!','250','150','true','2000','true','text');", Page);
            }
            else
            {
                AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作失败!','250','150','true','2000','true','text');", Page);
            }
            return;
        }
        if (type == "update")
        {
            Response.Redirect("FoodDetail.aspx?id=" + Convert.ToInt32(e.CommandArgument));
        }

        if (type == "set")
        {
            FoodinfoInfo model = dal.GetModel(Convert.ToInt32(e.CommandArgument));
            string InUser = model.InUse.Trim();
            if (InUser == "y")//下线
            {
                if (dal.UpdateValue("InUse", "n", "where Unid = (" + e.CommandArgument + ")") > 0)
                {
                    AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作成功1!','250','150','true','2000','true','text');", Page);
                }
                else
                {
                    AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作失败!','250','150','true','2000','true','text');", Page);
                }
                BindData();
            }
            else
            {
                if (dal.UpdateValue("InUse", "y", "where Unid = (" + e.CommandArgument + ")") > 0)
                {
                    AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作成功2!','250','150','true','2000','true','text');", Page);
                    BindData();
                }
                else
                {
                    AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:操作失败!','250','150','true','2000','true','text');", Page);
                }
            }
        }

        if (e.CommandName == "setstock")
        {
            string dataid = e.CommandArgument.ToString();
            TextBox tbProfit = e.Item.FindControl("tbRemains") as TextBox;

            string sql = " update Foodinfo set Remains='" + tbProfit.Text + "'where unid =" + dataid;

            if (WebUtility.excutesql(sql) > 0)
            {
                AlertScript.RegScript(this.Page, "tipsWindown('提示信息','text:操作成功!','250','150','true','1000','true','text');init();");
                BindData();
            }
            else
            {
                AlertScript.RegScript(this.Page, "tipsWindown('提示信息','text:操作失败!','250','150','true','1000','true','text');init();");
            }
        }


    }


    /// <summary>
    /// 批量设置折扣
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void setsalary_Click(object sender, EventArgs e)
    {
        Button bt = (Button)sender;
        string sql = "update Foodinfo set Remains = " + tbaddsalary.Text + " where ";

        sql += " " + SqlWhere;


        if (WebUtility.excutesql(sql) > 0)
        {
            AlertScript.RegScript(this.Page, "alert('设置成功','text:操作成功!','250','150','true','1000','true','text');init();");
            BindData();
        }
        else
        {
            AlertScript.RegScript(this.Page,  "alert('设置失败','text:操作失败!','250','150','true','1000','true','text');init();");
        }
    }


    protected void btSearch_Click(object sender, EventArgs e)
    {
        SqlWhere = "FPMaster= '" + UserHelp.GetUser_Togo().Unid + "' and InUse != 'd'";
        if (tbKeyword.Value != "")
        {
            SqlWhere += " and  FoodName like '%" + WebUtility.InputText(tbKeyword.Value) + "%'";
        }
        if (ddlFoodType.SelectedValue != "-1")
        {
            SqlWhere += " and FoodType = " + ddlFoodType.SelectedValue;
        }
        if (rblIsSpecial.SelectedValue != "-1")
        {
            SqlWhere += " and IsSpecial = " + rblIsSpecial.SelectedValue;
        }
        BindData();
    }

    /// <summary>
    /// 批量导入菜品数据 获取excel表格
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btAddExcel_Click(object sender, EventArgs e)
    {
        PinYin npy = new PinYin();
        string suffix = Path.GetExtension(this.fuFoodExcel.PostedFile.FileName);
        string sFile = "~/upload/foodexcel/" + HjNetHelper.GetQueryString("tid") + "" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + suffix;  //上传后文件的新名

        string errorinfo = "";

        if (suffix == ".xls" || suffix == ".XLS")
        {
            //保存文件

            try
            {
                this.fuFoodExcel.PostedFile.SaveAs(Server.MapPath(sFile));
            }
            catch (Exception ex)
            {
                AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:保存文件出错,稍后再试或联系技术人员','250','150','true','1000','true','text');", Page);
                return;
            }
            //获取商家的商品分类，excel中菜品的分类使用的是中文，需要进行匹配得到分类的编号保存到数据库菜品表中
            IList<EFoodSortInfo> foodtypelist = new List<EFoodSortInfo>();
            EFoodSort foodsortdal = new EFoodSort();
            int togoid = UserHelp.GetUser_Togo().Unid;
            foodtypelist = foodsortdal.GetListByTogoNum(togoid);

            if (foodtypelist == null || foodtypelist.Count < 1)
            {
                AlertScript.AjaxRegisterScript("tipsWindown('提示信息','text:商家菜品分类为空，至少需要一个菜品分类，请先添加菜品分类后进行导入操作','250','150','true','8000','true','text');", Page);
                return;
            }
            else
            {
                //解析文件并保存数据到数据库
                XlsDocument xls = new XlsDocument(Server.MapPath(sFile));
                Worksheet sheet = xls.Workbook.Worksheets["ShopFood"];

                FoodinfoInfo info;

                Foodinfo bll = new Foodinfo();
                bool havesort = false;
                //餐品名称、餐品原价、餐品现价、餐品库存、分类名称
                for (int i = 2; i < sheet.Rows.Count; i++) //excel中行数从1开始 此处第一行是行名称所以跳过第一个
                {
                    if (sheet.Rows[ushort.Parse(i.ToString())] != null && sheet.Rows[ushort.Parse(i.ToString())].CellCount > 0)
                    {
                        info = new FoodinfoInfo();

                        info.FPMaster = togoid;

                        info.FoodName = sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("1")).Value.ToString();
                        info.FPrice = Convert.ToDecimal(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("2")).Value);
                        info.FullPrice = Convert.ToDecimal(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("3")).Value);
                        info.MaxPerDay = Convert.ToInt32(sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("4")).Value);
                        //此处如果无内容则 列数会变成6，此时如果依然不做判断会报错超出数组范围，注意其他地方使用此类方法时注意此问题,
                        //空值的单元格并非为空而是直接超出数组范围
                        if (sheet.Rows[ushort.Parse(i.ToString())].CellCount > 6)
                        {
                            info.Taste = sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("6")).Value.ToString();
                        }
                        else
                        {
                            info.Taste = "";
                        }
                        //进行分类判断
                        foreach (EFoodSortInfo sortinfo in foodtypelist)
                        {
                            if (sortinfo.SortName == sheet.Rows[ushort.Parse(i.ToString())].GetCell(ushort.Parse("5")).Value.ToString().Trim())
                            {
                                info.FoodType = sortinfo.SortID;

                                havesort = true;
                                break;
                            }
                        }
                        if (!havesort)
                        {
                            info.FoodType = foodtypelist[0].SortID;//默认为使用第一个分类

                            errorinfo += "菜品[" + info.FoodName + "]未找到匹配的分类稍后请手动设置其分类；<br />";
                        }

                        havesort = false;


                        info.FoodNamePy = npy.convert(info.FoodName, true);
                        info.FoodNo = "";
                        info.FPActiveDate = DateTime.Now;
                        info.FPInDate = DateTime.Now;
                        info.InUse = "Y";
                        info.Picture = "";
                        info.Remains = info.MaxPerDay;
                        //info.Taste = "";
                        info.OrderNum = 0;
                        info.IsRecommend = 0;
                        info.IsSpecial = 0;
                        info.isauth = 1;
                        info.OpenTime = otime;
                        bll.Add(info);
                    }
                }
            }
            BindData();
            AlertScript.AjaxRegisterScript("$('#doing-mask').hide();tipsWindown('提示信息','text:批量导入成功,消息：" + errorinfo + "!','250','150','true','5000','true','text');", Page);//
        }
        else
        {
            AlertScript.AjaxRegisterScript("$('#doing-mask').hide();tipsWindown('提示信息','text:文件格式不正确，请上传excel文件!','250','150','true','5000','true','text');", Page);
        }
    }
}
